<template>
  <div class="my-clubs-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span class="title">我的社团</span>
          </div>
          <el-button 
            type="primary" 
            class="back-button"
            @click="goBack"
            :icon="ArrowLeft"
          >
            返回首页
          </el-button>
        </div>
      </template>
      
      <el-empty v-if="clubs.length === 0 && !pendingClub" description="暂未加入任何社团" />
      
      <!-- 展示待审核社团 -->
      <div v-else-if="pendingClub" class="pending-club-display-container">
         <h3 class="pending-club-title">您有一个正在创建中的社团申请:</h3>
        <el-card class="club-card pending-card-display">
          <img 
            :src="pendingClub.coverUrl || defaultCover" 
            class="club-cover" 
            alt="社团封面"
            @error="handleImageError"
          >
          <div class="club-info">
            <h3>{{ pendingClub.name }}</h3>
            <p class="description">{{ pendingClub.description }}</p>
            <div class="pending-footer">
              <el-tag type="warning" effect="dark">审核中</el-tag>
              <span class="creation-time">创建时间：{{ formatDate(pendingClub.createdAt) }}</span>
              <span class="applicant-info">申&nbsp;&nbsp;请&nbsp;&nbsp;人：{{ pendingClub.applicant }}</span>
            </div>
          </div>
        </el-card>
      </div>
      
      <div v-else class="clubs-grid">
        <div v-for="club in clubs" :key="club.id" class="club-wrapper">
          <el-card 
            class="club-card"
            @click="handleClubClick(club.id)"
          >
            <img 
              :src="club.coverUrl || defaultCover" 
              class="club-cover" 
              alt="社团封面"
              @error="handleImageError"
            >
            <div class="club-info">
              <h3>{{ club.name }}</h3>
              <p class="description">{{ club.description }}</p>
              <div class="club-footer">
                <div class="status-row">
                  <el-tag :type="club.clubActivitiesStatus === '正常' ? 'success' : 'warning'">
                    {{ club.clubActivitiesStatus }}
                  </el-tag>
                  <el-button 
                    type="danger" 
                    size="small" 
                    @click.stop="handleQuitClub(club.id)"
                    :loading="quitLoading === club.id"
                  >
                    退出社团
                  </el-button>
                </div>
                <div class="admin-info">
                  <p>管理员：{{ club.adminName }}</p>
                  <p>管理员账号：{{ club.adminAccount }}</p>
                  <p>创建时间：{{ formatDate(club.createdAt) }}</p>
                </div>
              </div>
            </div>
          </el-card>

          <!-- 活动列表现在将在弹框中显示，此处移除原有的内嵌活动列表 -->
          <!-- <div v-if="currentClubId === club.id" class="activities-wrapper">
            <div class="activities-container" v-loading="activitiesLoading">
              <el-empty v-if="!activities.length" description="暂无活动" />
              <div v-else class="activities-list">
                <el-card v-for="activity in activities" :key="activity.id" class="activity-card">
                  <img 
                    :src="activity.coverUrl || defaultCover" 
                    class="activity-cover" 
                    alt="活动封面"
                    @error="handleImageError"
                  >
                  <div class="activity-info">
                    <h3>{{ activity.title }}</h3>
                    <p class="description">{{ activity.description }}</p>
                    <div class="activity-footer">
                      <el-tag :type="activity.status === '1' ? 'success' : 'warning'">
                        {{ activity.status === '1' ? '进行中' : '已结束' }}
                      </el-tag>
                      <el-button 
                        type="primary" 
                        size="small"
                        @click="handleSignUp(activity.id)"
                        :disabled="activity.status !== '1'"
                      >
                        报名活动
                      </el-button>
                    </div>
                  </div>
                </el-card>
              </div>
            </div>
          </div> -->

        </div>
      </div>
    </el-card>

    <!-- 活动列表弹框 -->
    <el-dialog 
      v-model="activitiesDialogVisible" 
      title="社团活动" 
      width="80%" 
      top="5vh"
      destroy-on-close
    >
      <div class="activities-container" v-loading="activitiesLoading">
        <el-empty v-if="!activities.length" description="暂无活动" />
        <div v-else class="activities-list">
          <el-card v-for="activity in activities" :key="activity.id" class="activity-card">
            <img 
              :src="activity.coverUrl || defaultCover" 
              class="activity-cover" 
              alt="活动封面"
              @error="handleImageError"
            >
            <div class="activity-info">
              <h3>{{ activity.title }}</h3>
              <p class="description">{{ activity.description }}</p>
              <div class="activity-footer">
                <el-tag :type="activity.status === '1' ? 'success' : 'warning'">
                  {{ activity.status === '1' ? '进行中' : '已结束' }}
                </el-tag>
                <el-button 
                  type="primary" 
                  size="small"
                  @click="handleSignUp(activity.id)"
                  :disabled="activity.status !== '1'"
                >
                  报名活动
                </el-button>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </el-dialog>

  </div>
</template>

<script setup>
import { ArrowLeft } from '@element-plus/icons-vue'
import { ref, onMounted } from 'vue'
import { clubApi } from '../api'
import { ElMessage } from 'element-plus'
import defaultCover from '../assets/default-club-cover.jpg'
import { useRouter } from 'vue-router'

const router = useRouter()
const clubs = ref([])
const quitLoading = ref(null)
const activities = ref([])
const activitiesDialogVisible = ref(false)
const pendingClub = ref(null)

// 新增：获取用户信息的可复用函数
const getUserInfo = () => {
  const userInfo = JSON.parse(localStorage.getItem('userInfo'))
  if (!userInfo || !userInfo.id) {
    ElMessage.error('获取用户信息失败')
    return null
  }
  return userInfo
}

// 处理图片加载失败
const handleImageError = (e) => {
  e.target.src = defaultCover
}

// 格式化日期
const formatDate = (dateStr) => {
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 新增：查询社团创建进度
const checkClubCreateProgress = async (userId) => {
  try {
    const response = await clubApi.selectClubsCreateProgress(userId)
    if (response.code === 200 && response.data) {
      // 如果返回数据且 code 为 200，表示有正在创建中的社团
      pendingClub.value = response.data
    } else {
      // 没有正在创建中的社团或接口返回非 200
      pendingClub.value = null
    }
  } catch (error) {
    console.error('查询社团创建进度失败:', error)
    pendingClub.value = null // 查询失败也清空状态
  }
}

// 获取我的社团列表
const fetchMyClubs = async () => {
  try {
    const userInfo = getUserInfo()
    if (!userInfo || !userInfo.id) {
      ElMessage.error('获取用户信息失败')
      clubs.value = [] // 清空列表
      pendingClub.value = null // 确保清空 pendingClub
      return
    }

    const response = await clubApi.getMyClubs(userInfo.id)

    // 根据后端返回的 code 判断业务状态
    if (response.code === 200) {
      clubs.value = response.data
      pendingClub.value = null // 如果成功获取社团列表，清空 pendingClub
    } else if (response.code === 400 && response.message === '该用户暂未加入任何社团') {
       // 如果是后端返回的带特定消息的400业务码
       clubs.value = [] // 清空列表，显示暂无社团提示
       // 在用户未加入任何社团时，查询是否有正在创建中的社团
       await checkClubCreateProgress(userInfo.id) // Ensure this is awaited
       // 只有在没有待审核社团时，才显示未加入社团的提示
       if (!pendingClub.value) {
         ElMessage.info(response.message) // 使用 info 或 warning 类型提示用户
       }
    } else {
      // 其他非200且非特定400的业务错误
       ElMessage.error(response.message || '获取社团列表失败')
       clubs.value = []
       pendingClub.value = null // 确保清空 pendingClub
    }

  } catch (error) {
    console.error('获取社团列表失败:', error)
    // 捕获真正的 HTTP 错误（非 2xx 状态码）
    ElMessage.error('获取社团列表失败')
    clubs.value = [] // 清空列表
    pendingClub.value = null // 确保清空 pendingClub
  }
}

onMounted(() => {
  fetchMyClubs()
})

// 返回首页
const goBack = () => {
  router.push('/home')
}

// 退出社团
const handleQuitClub = async (clubId) => {
  try {
    const userInfo = getUserInfo()
    if (!userInfo || !userInfo.id) {
      ElMessage.error('获取用户信息失败')
      return
    }

    quitLoading.value = clubId
    
    // 这里需要调用退出社团的API
    const response = await clubApi.quitClub(clubId, userInfo.id)
    if (response.code === 200) {
      ElMessage.success('退出社团成功')
      // 直接从列表中移除退出的社团
      clubs.value = clubs.value.filter(club => club.id !== clubId)
      // 如果列表中没有社团了，清空当前展开的活动列表
      if (clubs.value.length === 0) {
        activities.value = [] // Clear activities if no clubs are left
        // 在退出最后一个社团后，也检查是否有正在创建的社团
        const userInfo = getUserInfo()
        if (userInfo && userInfo.id) {
           checkClubCreateProgress(userInfo.id)
        }
      }
    } else {
      ElMessage.error(response.message || '退出社团失败')
    }
  } catch (error) {
    console.error('退出社团失败:', error)
    ElMessage.error('退出社团失败')
  } finally {
    quitLoading.value = null
  }
}

// 格式化日期时间
const formatDateTime = (dateStr) => {
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const currentDialogClubId = ref(null) // To store the clubId for the currently open dialog
const activitiesLoading = ref(false)

// 处理社团卡片点击
const handleClubClick = async (clubId) => {
  try {
    currentDialogClubId.value = clubId // Store the clicked clubId
    activitiesLoading.value = true
    
    const response = await clubApi.getClubActivities(clubId)
    if (response.code === 200) {
      activities.value = response.data
      activitiesDialogVisible.value = true // Show the dialog
    } else {
      ElMessage.error(response.message || '获取活动列表失败')
      activities.value = [] // Clear activities on error
      activitiesDialogVisible.value = false // Keep dialog closed on error
    }
  } catch (error) {
    console.error('获取活动列表失败:', error)
    ElMessage.error('获取活动列表失败')
    activities.value = [] // Clear activities on error
    activitiesDialogVisible.value = false // Keep dialog closed on error
  } finally {
    activitiesLoading.value = false
  }
}

// 处理活动报名
const handleSignUp = async (activityId) => {
  try {
    const userInfo = getUserInfo()
    if (!userInfo || !userInfo.id) {
      ElMessage.error('获取用户信息失败')
      return
    }
    
    const response = await clubApi.signUpActivity(activityId, userInfo.id)
    if (response.code === 200) {
      ElMessage.success('报名成功')
      // Re-fetch activities for the current dialog's club
      if (currentDialogClubId.value) {
        handleClubClick(currentDialogClubId.value) // Call handleClubClick to refresh the list in the dialog
      }
    } else {
      ElMessage.error(response.message || '报名失败')
    }
  } catch (error) {
    console.error('报名失败:', error)
    ElMessage.error('报名失败')
  }
}
</script>

<style scoped>
.my-clubs-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f7fafc 0%, #e3f6f5 100%);
  padding: 32px 0 40px 0;
}

.box-card {
  max-width: 1200px;
  margin: 0 auto 32px auto;
  border-radius: 16px;
  box-shadow: 0 4px 24px 0 rgba(100, 200, 180, 0.10);
  border: 1.5px solid #e3e8ee;
  background: #fff;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 18px 0 0 0;
}
.header-left {
  display: flex;
  align-items: center;
}
.title {
  font-size: 24px;
  font-weight: bold;
  color: #22577a;
  margin: 0;
  letter-spacing: 1.5px;
}
.back-button {
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 5px;
  border-radius: 8px;
  background: linear-gradient(90deg, #bfc6d1 0%, #e0e4ea 100%);
  border: none;
  color: #555;
}
.back-button:hover {
  transform: translateX(-5px);
  background: linear-gradient(90deg, #e0e4ea 0%, #bfc6d1 100%);
  color: #333;
}

.clubs-grid {
  display: grid;
  /* grid-template-columns: repeat(auto-fill, minmax(340px, 1fr)); */
  grid-template-columns: repeat(auto-fill, 340px); /* Set fixed column width */
  gap: 28px;
  margin-top: 28px;
  position: relative;
  /* Optional: Center the grid if columns don't fill the width */
  justify-content: center;
}
.club-wrapper {
  position: relative;
  width: 100%;
  display: flex;
  flex-direction: column;
}
.club-card {
  width: 100%;
  height: 500px; /* Set a fixed height for consistent card size */
  cursor: pointer;
  margin-bottom: 0; /* Removed bottom margin as activities are not inline */
  border-radius: 16px;
  box-shadow: 0 4px 24px 0 rgba(100, 200, 180, 0.10);
  border: 1.5px solid #e3e8ee;
  background: #fff;
  transition: transform 0.3s, box-shadow 0.3s;
}
.club-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 32px 0 rgba(100, 200, 180, 0.18);
}
.club-cover {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 16px 16px 0 0;
}
.description {
  margin: 10px 0;
  color: #666;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
.club-info {
  padding: 18px;
  flex: 1; /* Ensure club info takes available space */
  display: flex;
  flex-direction: column;
}
.club-info h3 {
    margin-top: 0;
    margin-bottom: 10px;
    font-size: 18px;
    color: #333;
}
.club-footer {
  display: flex;
  justify-content: space-between;
  align-items: center; /* Align status row and admin info vertically */
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #eee;
}
.status-row {
  display: flex;
  flex-direction: column; /* Vertical arrangement */
  align-items: flex-start; /* Left alignment */
  gap: 8px; /* Space between items */
}
.admin-info {
  margin-top: 10px;
  font-size: 14px;
  color: #666;
  display: block; 
  text-align: right; 
}
.admin-info p {
  margin: 4px 0; 
  line-height: 1.4;
}
/* Removed styles for inline activities wrapper */
/*
.activities-wrapper {
  position: static;
  left: auto;
  top: auto;
  z-index: auto;
  width: 100%;
  max-width: 100%;
  transition: all 0.3s ease;
  box-sizing: border-box;
  padding-left: 0;
  display: block;
  overflow: hidden;
  height: auto;
}
*/

/* Styles for the activities container within the dialog */
.activities-container {
  background: #fff; /* Keep background for dialog content */
  border-radius: 12px; /* Keep border radius */
  box-shadow: 0 2px 12px 0 rgba(100, 200, 180, 0.10); /* Keep shadow */
  padding: 18px; /* Keep padding */
  width: 100%; /* Take full width of dialog content area */
  box-sizing: border-box; /* Include padding and border in element's total width */
  border: 1.5px solid #e3e8ee; /* Keep border */
}
.activities-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 18px;
}
.activity-card {
  border-radius: 14px;
  box-shadow: 0 4px 24px 0 rgba(100, 200, 180, 0.10);
  border: 1.5px solid #e3e8ee;
  background: #fff;
  transition: transform 0.3s, box-shadow 0.3s;
}
.activity-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 32px 0 rgba(100, 200, 180, 0.18);
}
.activity-cover {
  width: 100%;
  height: 150px;
  object-fit: cover;
  border-radius: 14px 14px 0 0;
}
.activity-info {
  padding: 15px;
  flex: 1;
  display: flex;
  flex-direction: column;
}
.activity-info h3 {
  margin-top: 0;
  margin-bottom: 8px;
  font-size: 16px;
  color: #333;
}
.activity-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #eee;
}
.el-tag {
  border-radius: 6px;
  padding: 0 10px;
  height: 26px;
  line-height: 26px;
  font-size: 14px;
}
.el-button {
  border-radius: 8px;
  padding: 8px 20px;
  font-weight: 500;
  font-size: 15px;
  transition: all 0.3s;
}
.el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(100, 200, 180, 0.12);
}
.el-button--primary {
  background: linear-gradient(90deg, #8fd6e1 0%, #b8e1dd 100%);
  border: none;
  color: #22577a;
}
.el-button--primary:hover {
  background: linear-gradient(90deg, #b8e1dd 0%, #8fd6e1 100%);
  color: #38a3a5;
}
.el-button--danger {
  background: linear-gradient(90deg, #ffb4a2 0%, #ffdac1 100%);
  border: none;
  color: #b0413e;
}
.el-button--danger:hover {
  background: linear-gradient(90deg, #ffdac1 0%, #ffb4a2 100%);
  color: #e76f51;
}
.el-empty {
  margin: 60px auto;
}
::-webkit-scrollbar {
  width: 8px;
  background: #e3f6f5;
}
::-webkit-scrollbar-thumb {
  background: #b8e1dd;
  border-radius: 4px;
}

/* 待审核社团展示容器 */
.pending-club-display-container {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  align-items: flex-start; /* Align items to the start (left) */
}

.pending-club-title {
   color: #ff9800;
   margin-bottom: 15px;
   font-size: 20px;
   font-weight: bold;
   text-align: left; /* Align title to the left */
}

/* 待审核社团卡片特定样式 */
.pending-card-display {
  border-color: #ff9800; /* 橙色边框突出待审核状态 */
  max-width: 400px; /* 限制卡片最大宽度 */
}

/* 待审核社团卡片底部的样式 */
.pending-footer {
  display: flex; /* Use flexbox */
  flex-direction: column; /* Arrange items vertically */
  align-items: flex-start; /* Align items to the start of the column (left) */
  gap: 8px; /* Add space between items */
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.pending-footer .creation-time {
    font-size: 14px;
    color: #666;
}

.pending-footer .applicant-info {
    font-size: 14px;
    color: #666;
}
</style>